import { View, Text, Image } from '@tarojs/components'
import Taro, { useDidShow, useLoad } from '@tarojs/taro';
import classNames from 'classnames';
import { useState } from 'react'
import axios from '@/request/index'
import { useWebStore } from '@/store/web';
import './index.scss'

export default function News() {

  const [tab, setTab] = useState(0);
  const [newsList, setNewsList] = useState<any[]>([]);
  const { setUrl } = useWebStore()

  useLoad(() => {
    console.log('Page loaded.')
  })
  const initList = async (index?: any) => {
    const newsRes = await axios.get('/catalog/homePage', {
      params: {
        type: 2,
        sortType: index >=0 ? index : tab
      }
    })
    if (newsRes && newsRes.data) {
      setNewsList(newsRes.data)
    }
  }
  useDidShow(async () => {
    initList();
  });

  const onSelectTab = (index) => {
    setTab(index);
    initList(index);
  }

  const onClickItem = (item) => {
    setUrl(item.content)
    Taro.navigateTo({
      url: `/package-home/pages/WebView/index`
    })
  }


  return (
    <View className='news bg-[#F5F5F5] min-h-screen pb-[80px]'>
      <View className='bg-white h-[112px] flex flex-row items-center px-[40px]'>
        <View
          className=
          {
            classNames('text-[36px]',
              tab === 0 ? 'text-[#5959F8] ' : 'text-[#000] ')
          }
          onClick={() => onSelectTab(0)}
        >
          推荐
        </View>
        <View
          className='text-[#000] text-[36px] ml-16 relative'
          onClick={() => onSelectTab(1)}
        >
          最新
          <Image src={tab === 1 ? require('./images/tab.png') : require('./images/tab_normal.png')} className='w-[30px] h-[8px] absolute -bottom-1 left-[50%] -translate-x-[50%]' />
        </View>
      </View>
      <View className='px-4'>
        {
          newsList.map((item, index) => {
            return (
              <View 
                key={index} 
                onClick={() => onClickItem(item)}
                className='mt-[50px] flex flex-col bg-[rgba(229,229,229,0.5)] rounded-lg overflow-hidden'>
                <Image src={item.cover} className='h-[280px] w-full bg-[#000]' />
                <View className='h-[80px] px-3 text-[28px] text-[#000] leading-[80px]'>
                  {item.title}
                </View>
                <View className='bg-[#FFF] flex flex-row items-center justify-between px-3 py-2'>
                  <Text className='text-[24px] text-[#000]'>{item.author}</Text>
                  <Text className='text-[24px] text-[#000] ml-2'>{item.time}</Text>
                </View>
              </View>

            )
          })
        }
      </View>
    </View>
  )
}
